package com.foreveross.bsl;

import java.util.ArrayList;
import java.util.Set;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.foreveross.bsl.manager.ApplicationSyncListener;
import com.foreveross.bsl.manager.AutoDownloadHelper;
import com.foreveross.bsl.manager.CubeModuleManager;
import com.foreveross.bsl.model.CubeApplication;
import com.foreveross.bsl.model.CubeModule;
import com.foreveross.bsl.util.BroadcastConstans;
import com.foreveross.bsl.util.Preferences;
import com.foreveross.chameleon.AppStatus;
import com.foreveross.chameleon.base.BaseFragmentActivity;
import com.foreveross.chameleon.update.AutoCheckUpdateListener;
import com.foreveross.chameleon.update.CheckUpdateTask;
import com.foreveross.chameleonsdk.config.CubeConstants;
import com.foreveross.chameleonsdk.config.URL;
import com.foreveross.data.table.MessageDataModel;
import com.foreveross.push.url.MessageConstants;
import com.google.gson.Gson;

public class CmanagerModuleActivity extends BaseFragmentActivity {
	String url = "";
	IntentFilter intentFilter = new IntentFilter();
	BroadcastReceiver receiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (BroadcastConstans.ReceiveMessage.equals(intent.getAction())) {
				new RefreshThread().start();
			} else if (BroadcastConstans.RefreshMainPage.equals(intent
					.getAction())) {
				String identifier = intent.getStringExtra("identifier");
				String type = intent.getStringExtra("type");
				CubeModule module = CubeModuleManager.getInstance()
						.getIdentifier_new_version_map().get(identifier);
				if (module == null) {
					module = CubeModuleManager.getInstance()
							.getCubeModuleByIdentifier(identifier);
					if (module != null) {
						if (module.isAutoDownload()) {
							// endAnimAutoDownload();
						}
					}
				}
				refreshMainPage(identifier, type, module);
			} else if (BroadcastConstans.RefreshModule.equals(intent
					.getAction())) {

				String identifier = intent.getStringExtra("identifier");
				String type = intent.getStringExtra("type");
				CubeModule module = CubeModuleManager.getInstance()
						.getIdentifier_new_version_map().get(identifier);
				if (module == null) {
					module = CubeModuleManager.getInstance()
							.getCubeModuleByIdentifier(identifier);
				}
				refreshModule(identifier, type, module);

			} else if (BroadcastConstans.UpdateProgress.equals(intent
					.getAction())) {
				String identifier = intent.getStringExtra("identifier");
				int progress = intent.getIntExtra("progress", 0);
				updateProgress(identifier, progress);
			}else if(BroadcastConstans.MODULE_AUTODOWNLOAD_FINISH.equals(intent.getAction())) {
				//显示自动下载
				autodownloadlayout.setVisibility(View.GONE);
				AutoDownloadHelper.getInstance().setAutoDownloadCount(0);
				progress.setText("已下载："+"0"+"，总计需下载："+"0");
			}else if(BroadcastConstans.MODULE_AUTODOWNLOAD_START.equals(intent.getAction())) {
				//关闭自动下载
				autodownloadlayout.setVisibility(View.VISIBLE);
			}
			else if (BroadcastConstans.MODULE_AUTODOWNLOAD_PROGERSS.equals(intent.getAction())) {
				int count = AutoDownloadHelper.getInstance().getAutoDownloadCount();
				int downLoadCount = AutoDownloadHelper.getInstance().getProgressCount();
				progress.setText("已下载："+(count-downLoadCount)+"，总计需下载："+count);
			}  
			else if (BroadcastConstans.SecurityChange.equals(intent.getAction())) {
				String username = Preferences.getUserName(CmanagerModule.sharePref);
				CubeApplication.getInstance(CmanagerModuleActivity.this).syncPrivilege(true, CmanagerModuleActivity.this,
						username, new ApplicationSyncListener() {

							@Override
							public void syncStart() {

							}

							@Override
							public void syncFinish() {
								refreshMainPageEvent();
							}

							@Override
							public void syncFail() {

							}
						});
			}  else if (BroadcastConstans.SecurityRefreshMainPage.equals(intent
					.getAction())) {
				Log.i("", "SecurityRefreshMainPage ================== ");
				CubeApplication apCubeApplication = CubeApplication
						.getInstance(context);
				Set<CubeModule> modules = apCubeApplication.getModules();
				for (CubeModule cubeModule : modules) {
					refreshMainPage(cubeModule.getIdentifier(), "main",
							cubeModule);
					break;
				}
//				Intent intent2 = new Intent();
//				String title = Preferences.getToken(Application.sharePref);
//				Notifier.notifyInfo(context, R.drawable.about_logo, 123, "权限发生改变", title, intent2);
//				Toast.makeText(application.getApplicationContext(), "权限改变",
//						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		url = "file:///android_asset/www/phone/index.html";
//		url = URL.PHONE_MAIN_URL;
		if(isPad()){
			url = URL.PAD_MAIN_URL;
		}else{
			url = URL.PHONE_MAIN_URL;
		}
		loadMainContent(url);
		intentFilter.addAction(BroadcastConstans.MODULE_AUTODOWNLOAD_FINISH);
		intentFilter.addAction(BroadcastConstans.MODULE_AUTODOWNLOAD_START);
		intentFilter.addAction(BroadcastConstans.MODULE_AUTODOWNLOAD_PROGERSS);
		intentFilter.addAction(BroadcastConstans.ReceiveMessage);
		intentFilter.addAction(BroadcastConstans.UpdateProgress);
		intentFilter.addAction(BroadcastConstans.RefreshModule);
		intentFilter.addAction(BroadcastConstans.RefreshMainPage);
		intentFilter.addAction(BroadcastConstans.SecurityChange);
		intentFilter.addAction(BroadcastConstans.SecurityRefreshMainPage);
		registerReceiver(receiver, intentFilter);
		
		
		Intent i = getIntent();
		if(i!=null){
			showModule(i);
		}
	}
	
	public void showModule(Intent intent) {
		Intent i =intent;
		if(i!=null){
			String moduleIdentifier = i.getStringExtra("moduleIdentifier");
			String className = i.getStringExtra("className");
			//String params = i.getStringExtra("parameters");
			String params[] = i.getStringArrayExtra("parameters");
			
			CubeModule module = CubeModuleManager.getInstance().getModuleByIdentify(moduleIdentifier);
			if(module!=null){
				Intent moduleIntent = null;
				if(module.getModuleType() != CubeModule.INSTALLED) {
					String identifier = MessageConstants.MESSAGE_IDENTIFIER;
					 module = CubeModuleManager.getInstance().getModuleByIdentify(identifier);
				}
				moduleIntent =  CubeModuleManager.getInstance().showModule(this,module);
				if(moduleIntent!=null){
					if(params!=null && params.length!=0){
						moduleIntent.putExtra("parameters", params);
					}
					if(className!= null&&!className.equals("")) {
						
						moduleIntent.setClassName(getApplicationContext(), className);
					}
					startActivity(moduleIntent);
				}
			}
		}
		checkUpdate(url);
		
	}
	
	private AutoCheckUpdateListener acuListener;
	private CheckUpdateTask updateTask;
	public void checkUpdate(String url) {
		System.out.println("checkUpdate");
		//&& url.contains("login") 修改触发更新监听
		if (url != null ) {
			System.out.println("checkUpdate====!=null");
			acuListener = new AutoCheckUpdateListener(this);
			updateTask = new CheckUpdateTask(CubeApplication.getInstance(this),acuListener);
			updateTask.execute();
		}
	}
	
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		showModule(intent);
		
		
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
		if(updateTask.getStatus()!=AsyncTask.Status.FINISHED){
			updateTask.cancel(true);
		}
	}

	public void refreshMainPage(String identifier, String type,
			CubeModule module) {
		String moduleMessage = new Gson().toJson(module);
		setMainJavaScript("refreshMainPage('" + identifier + "','" + type
				+ "','" + moduleMessage + "')");
//		appView.sendJavascript("refreshMainPage('" + identifier + "','" + type
//				+ "','" + moduleMessage + "')");
	}

	public void refreshModule(String identifier, String type, CubeModule module) {
		String moduleMessage = new Gson().toJson(module);
		setMainJavaScript("refreshModule('" + identifier + "','" + type
				+ "','" + moduleMessage + "')");
//		appView.sendJavascript("refreshModule('" + identifier + "','" + type
//				+ "','" + moduleMessage + "')");
	}

	public void updateProgress(String identifier, int progress) {
		setMainJavaScript("updateProgress('" + identifier + "','"
				+ progress + "')");
//		appView.sendJavascript("updateProgress('" + identifier + "','"
//				+ progress + "')");
	}

	public void receiveMessage(final String identifier, final int count,
			boolean display) {
		setMainJavaScript("receiveMessage('" + identifier + "'," + count
				+ "," + display + ")");
//		appView.sendJavascript("receiveMessage('" + identifier + "'," + count
//				+ "," + display + ")");
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == CubeConstants.LOGIN_SUCCESS) {
			String username = data.getStringExtra("username");
			CubeApplication.getInstance(this).syncPrivilege(true, this,
					username, new ApplicationSyncListener() {

						@Override
						public void syncStart() {

						}

						@Override
						public void syncFinish() {

						}

						@Override
						public void syncFail() {

						}
					});
		}
	}
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		Dialog dialog = new AlertDialog.Builder(this)
		.setTitle("提示")
		.setMessage("确定退出 ？")
		.setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.dismiss();
					}
				})
		.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						AppStatus.USERLOGIN = false;
						dialog.dismiss();
						finish();
					}
		}).create();
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_UP) {
				if(popFragment()){
					return true;
				}
				if(dialog.isShowing()) {
					dialog.dismiss();
					return true;
				}else {
					dialog.show();
					return true;
				}
			}
		}
		return super.dispatchKeyEvent(event);
	}
	
	class RefreshThread extends Thread{
		@Override
		public void run() {
			try {
				CubeModuleManager cubeModuleManager = CubeModuleManager.getInstance();
				MessageDataModel messageDataModel = new MessageDataModel(CmanagerModuleActivity.this);
				for (String  identifier : cubeModuleManager.getIdentifier_map().keySet()) {
					if (!identifier.equals(MessageConstants.MESSAGE_IDENTIFIER)){
						int count = messageDataModel
								.getIdentifierUnReadCount(identifier);
						CubeModule module = CubeModuleManager.getInstance()
								.getCubeModuleByIdentifier(identifier);
						module.setMsgCount(count);
						receiveMessage(identifier, count, true);
					}
				}
				int messageCount = messageDataModel
						.getUnReadCount();
				CubeModule messageModule = CubeModuleManager.getInstance()
						.getCubeModuleByIdentifier(
								MessageConstants.MESSAGE_IDENTIFIER);
				messageModule.setMsgCount(messageCount);
				receiveMessage(MessageConstants.MESSAGE_IDENTIFIER, messageCount, true);
				CubeApplication cubeAPplication =   CubeApplication.getInstance(CmanagerModuleActivity.this);
				CubeApplication.getInstance(CmanagerModuleActivity.this).save(cubeAPplication);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		System.out.println("cManagerModule activity resume");
		new RefreshThread().start();
		CubeApplication apCubeApplication = CubeApplication
				.getInstance(this);
		Set<CubeModule> modules = apCubeApplication.getModules();
		for (CubeModule cubeModule : modules) {
			refreshMainPage(cubeModule.getIdentifier(), "main",
					cubeModule);
			break;
		}
		
		super.onResume();

	}
	
	public void refreshMainPageEvent(){
		CubeApplication apCubeApplication = CubeApplication
				.getInstance(this);
		Set<CubeModule> modules = apCubeApplication.getModules();
		for (CubeModule cubeModule : modules) {
			refreshMainPage(cubeModule.getIdentifier(), "main",
					cubeModule);
			break;
		}
	}
	
}
